package com.netmi.myjectpack.paging.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.netmi.myjectpack.R
import com.netmi.myjectpack.paging.bean.RepoBean

/**
 * @author tgw
 * @date 2022/5/16
 * @describe
 */
class RepoAdapter : PagingDataAdapter<RepoBean, RepoAdapter.ViewHolder>(COMPARATOR) {

    companion object {
        private val COMPARATOR = object : DiffUtil.ItemCallback<RepoBean>() {
            override fun areItemsTheSame(oldItem: RepoBean, newItem: RepoBean): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: RepoBean, newItem: RepoBean): Boolean {
                return oldItem == newItem
            }
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val name: TextView = itemView.findViewById(R.id.name_text)
        val description: TextView = itemView.findViewById(R.id.description_text)
        val starCount: TextView = itemView.findViewById(R.id.star_count_text)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.page3_repo_item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val repo = getItem(position)
        if (repo != null) {
            holder.name.text = repo.name
            holder.description.text = repo.description
            holder.starCount.text = repo.starCount.toString()
        }
    }

}


class BaseRepoAdapter : BasePagingAdapter<RepoBean>(COMPARATOR) {

    companion object {
        private val COMPARATOR = object : DiffUtil.ItemCallback<RepoBean>() {
            override fun areItemsTheSame(oldItem: RepoBean, newItem: RepoBean): Boolean {
                //判断是否是同一个item，可以在这里处理   判断是否是相同item的逻辑，比如id之类的
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: RepoBean, newItem: RepoBean): Boolean {
                //判断数据是否发生改变，这个  方法会在上面的方法返回true时调用，  因为虽然item是同一个，但有可能item的数据发生了改变
                return oldItem == newItem
            }
        }
    }



    override fun getItemLayout(position: Int): Int {
      return  R.layout.page3_repo_item
    }

    override fun onItemClick(data: RepoBean?) {
    }

    override fun bindData(helper: ItemHelper, repo: RepoBean?) {

        if (repo != null) {
            helper.setText(R.id.name_text,repo.name)
            helper.setText(R.id.description_text,repo.description)
            helper.setText(R.id.star_count_text,repo.starCount.toString())
        }
    }

}